<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
<script>
  $(document).ready(function(){
        
    var prefs = new gadgets.Prefs();
         
    var entityId = prefs.getString("entityid");
    var gmailAccount = prefs.getString("email");
    var baseUrl =  prefs.getString("base");
    var mailerUrl =  prefs.getString("mailurl");
          
    var email = null;
    var messageId = null;
          
    var TARGET = "erecruit";
          
    // take from the extractor matches messageId and email
    var matches = google.contentmatch.getContentMatches();
    for (var matchGroupKey in matches) {
      var keyedValues = matches[matchGroupKey];
      for (var key in keyedValues) {
        switch (key){
          case "message_id":
            messageId = keyedValues[key];
            break;
            case "sender_email":
            email = keyedValues[key];
            break;
        }
      }
    }
          
    //alert("entityid: " + entityId + "\nbaseUrl: " + baseUrl + "\nemail: " + email + "\nmessageId:" + messageId);
          
    // Initalize all links as disabled
    $("a").addClass('disabled').css("text-decoration", "none").click(function(event){
      event.preventDefault();
    });
          
    // but dashboard link is an exception: it is always available and points to base url
    var linkAttr = {
      target: TARGET,
      href: baseUrl
    };
    $("#dashboard").removeClass('disabled').unbind('click').attr(linkAttr);
   
    // call the service to try to find the message sender by email
    var request = {
      entityid: entityId,
			account: gmailAccount,          
      emails: [email]
    };
    var ajaxSettings = {
      url: baseUrl + "/api/email/findbyemail",
      type: "post",
      dataType: 'json', // expect the answer in json format
      data: JSON.stringify(request)
    };
 
    //$.ajax(ajaxSettings)
    //.success(HandleServiceResponse)
    //.error( function(){
    //});
    //******* this following fragment is for debugging only: we create a fakeResponse *******
    var CANDIDATE_REFID = "226198"; // 6
    var CONTACT_REFID = "401"; // 2
    setTimeout(1000, HandleServiceResponse({    
      Success: true,
      Result: email !== "abeliaev@hotmail.com" ? [] : [
        { 
          Name: "John Smith", 
          Type: 6,
          ReferenceID: CANDIDATE_REFID
        }
      ]
    }));
    //******** comment/delete the above fragment and uncomment actual ajax call **************
          
    function HandleServiceResponse(response){
            
      if (!response.Success){
        // if we have a good response from the service but the service tells it actually failed:
        // for now do nothing
        return;
      }
            
      // service did not failed: the result contains an array of about items: either empty or otherwise the first item is abou the sender
            
      // this is helper object used to generate required anchor href url base on the parameters 
      var params = {
            
        // generate url for direct call the required erecruit page
        setHref: function(attr){
          attr.href = baseUrl + "/Recruiter/?op1=" + this.typename + "&op2=" + this.action + "&op3=" + (this.refid ? this.refid : "") + "&op4=" + (this.qs ? encodeURIComponent(this.qs) : "");
          return attr;
        },
              
        // generate url for calling intermidiate web page to handle email message data and then redirect to the requested erecruit page
        setRedirectHref: function(attr){
          this.setHref(attr);
          attr.href = mailerUrl + "?entityid=" + entityId + "&id=" + messageId + "&base=" + attr.href.replace("?", "&") + "&self=" + encodeURIComponent(mailUrl);
          return attr;
        }
      };
            
      if (response.Result.length > 0){
              
        // known sender
              
        var aboutItem = response.Result[0];
                            
        params.typename = aboutItem.Type === 2 ? "contact" : "candidate";
        params.refid = aboutItem.ReferenceID;
        params.action = "manage"; 
              
        // enable all appropriate gadget link controls and set appropriate hrefs
         
        $("#openrecord").removeClass('disabled').unbind('click').attr(params.setHref(linkAttr));
              
        params.qs = "tiptrigger=btnAddNewScheduledItem";
        $("#scheduled").removeClass('disabled').unbind('click').attr(params.setHref(linkAttr));
              
        params.qs = "tab=Attachments&FromFile=";
        $("#upload").removeClass('disabled').unbind('click').attr(params.setRedirectHref(linkAttr));
               
        $("#notemenu").menu(); // create/activate note menu
        $("#noteicon").removeClass('disabled').unbind('click');
              
        params.qs = "attachment=&tiptrigger=btnAddNewNote&FromFile=";
        $("#note").removeClass('disabled').unbind('click').attr(params.setRedirectHref(linkAttr));
              
        params.qs = "tiptrigger=btnAddNewNote&FromFile=";
        $("#notebody").removeClass('disabled').unbind('click').attr(params.setRedirectHref(linkAttr));
              
        params.qs = "tiptrigger=btnAddNewNote";
        $("#noteblank").removeClass('disabled').unbind('click').attr(params.setHref(linkAttr));
              
        params.qs = (typename === "contact" ? "contactid=" + params.refid : "");
        params.typename = "position"; 
        params.refid = ""; 
        params.action = "new"; 
        $("#position").removeClass('disabled').unbind('click').attr(params.setRedirectHref(linkAttr));
            
      } else {
              
        // unknown sender

        params.action = "new";
              
        params.typename = "position";
        $("#position").removeClass('disabled').unbind('click').attr(params.setRedirectHref(linkAttr));
                               
        params.typename = "contact";
        $("#contact").removeClass('disabled').unbind('click').attr(params.setRedirectHref(linkAttr));
                  
        params.typename = "candidate";
        $("#candidate").removeClass('disabled').unbind('click').attr(params.setRedirectHref(linkAttr));
            
        params.typename = "general";
        params.action = "addemail";
        params.qs = "Email=" + email;
        $("#addemail").removeClass('disabled').unbind('click').attr(params.setHref(linkAttr));
      }
    }
          
  });
</script>
      
<style>
    .mail {text-align:center; font-family:tahoma; font-size:small;}
    a {text-decoration: none}
    A.disabled {
        cursor: default;
    }
    a.disabled img {
      opacity:0.4;
      filter:alpha(opacity=40); /* For IE8 and earlier */
    }
    ul {list-style-type: none; margin:0; padding: 0}
          
    .li {margin-left:0;}
          
</style>
<table class="mail">
  <tr>
    <td valign="top">
          <a id="dashboard">
            <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/Dashboard.png" title="Go to the erecruit dashboard"/>
          </a>
    </td>
    <td valign="top" align="left">
        <div>
            <a id="candidate">
              <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/NewCandidate.png/" title="Add a new candidate from this email">
            </a>
            <a id="contact">
              <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/NewContact.png" title="Add a new contact from this email"/>
            </a>
            <a id="position">
              <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/NewPosition.png" title="Add a new position from this email">
            </a>
        </div>
        <div>
            <a id="openrecord">
              <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/Open.png/" title="Open the record of the sender of this email">
            </a>
            <a id="upload">
              <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/UploadAttachment.png" title="Upload the attachment(s) in this email"/>
            </a>
            <a id="scheduled">
              <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/NewScheduledItem.png" title="Create a scheduled item from this email"/>
            </a>
        </div>
        <div>
          <a id="addemail">
            <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/NewEmail.png" title="Add Email to Contact or Candidate"/>
          </A>
        </div>
    </td>
    <td align="right">
      <ul id="notemenu" valign="top" style="width:50px">
          <li><a href="#">&nbsp;</a></li>
          <li style="height:40px;">
            <a id="noteicon" href="#">
              <img src="http://erecruit-gadgets.googlecode.com/svn/trunk/Images/NewNote.png" width="40" title="Add a note from this email"/>
            </a>
            <ul style="text-align:left;width:120px;display:none">
              <li>
                <a id="note">From Attachment</a>
              </li>
              <li>
                <a id="notebody">From Body</a>
              </li>
              <li>
                <a id="noteblank">Blank Note</a>
              </li>
            </ul>
          <li>
          <li><a href="#">&nbsp;</a></li>
        </ul>         
    </td>
    </tr>
</table>